<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>操作系统⚡内存管理 | 小李博客</title><meta name="keywords" content="操作系统"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="内存管理 内存基础 什么是内存  内存是用于存放数据的硬件，程序执行前需要先放到内存中才能被CPU处理  储存单元按字节编址：一个存储单元1字节，8个二进制位，1字节对应一个地址按字长编址：一个存储单元1个字长，字长16位的计算机一个存储单元16个二进制位2^10&#x3D;1K           2^20&#x3D;1M               2^30&#x3D;1G4G内存的地址长度: 4*2^30&#x3D;2^32  ，">
<meta property="og:type" content="article">
<meta property="og:title" content="操作系统⚡内存管理">
<meta property="og:url" content="http://xiaoliblog.cn/page/os04.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="内存管理 内存基础 什么是内存  内存是用于存放数据的硬件，程序执行前需要先放到内存中才能被CPU处理  储存单元按字节编址：一个存储单元1字节，8个二进制位，1字节对应一个地址按字长编址：一个存储单元1个字长，字长16位的计算机一个存储单元16个二进制位2^10&#x3D;1K           2^20&#x3D;1M               2^30&#x3D;1G4G内存的地址长度: 4*2^30&#x3D;2^32  ，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png">
<meta property="article:published_time" content="2021-01-15T05:16:33.486Z">
<meta property="article:modified_time" content="2021-02-06T12:42:21.453Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/os04"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-02-06 20:42:21'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">操作系统⚡内存管理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-15T05:16:33.486Z" title="发表于 2021-01-15 13:16:33">2021-01-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-02-06T12:42:21.453Z" title="更新于 2021-02-06 20:42:21">2021-02-06</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%9F%BA%E7%A1%80/">计算机基础</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%9F%BA%E7%A1%80/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="操作系统⚡内存管理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="内存管理"><a href="#内存管理" class="headerlink" title="内存管理"></a>内存管理</h1><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/339f84440daad4b17a82464ae8c6d840.png"></p>
<h2 id="内存基础"><a href="#内存基础" class="headerlink" title="内存基础"></a>内存基础</h2><ul>
<li><p>什么是内存<br>  内存是用于存放数据的硬件，<strong>程序执行前需要先放到内存中才能被CPU处理</strong></p>
<ul>
<li><strong>储存单元</strong><br>按<strong>字节</strong>编址：一个存储单元1字节，8个二进制位，1字节对应一个地址<br>按<strong>字长</strong>编址：一个存储单元1个字长，字长16位的计算机一个存储单元16个二进制位<br>2^10=1K           2^20=1M               2^30=1G<br>4G内存的地址长度: 4*2^30=2^32  ，所以需要32个二进制位(32位操作系统最大支持4GB内存，指针大小4字节)</li>
<li><strong>内存地址</strong><br>内存从0开始，每一个地址对应一个<strong>存储单元</strong></li>
</ul>
</li>
<li><p>进程运行的基本原理</p>
<ul>
<li><strong>指令的工作原理</strong><br>CPU按照程序段的指令去内存某个位置存取数据，一条 指令由操作码+若干参数组成<br>编译生成的指令中一般使用逻辑地址</li>
<li><strong>逻辑地址/物理地址</strong><br>逻辑地址（相对地址）<br>物理地址（绝对地址）</li>
</ul>
</li>
<li><p>从写程序到程序运行</p>
<ol>
<li><strong>编辑源文件</strong></li>
<li><strong>编译</strong><br>源代码文件(.c)生成目标模块(.o)，将高级语言翻译为机器语言<br>每一个目标模块都具有独立的逻辑地址 0-xxx</li>
<li><strong>链接</strong><br>目标模块生成装入模块(可执行文件,如.exe)，链接完成使得各模块形成整体的链接地址</li>
<li><strong>装入(载)</strong><br>将装入模块装入内存运行，装入后形成物理地址</li>
</ol>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/8e00f6dbac6c69dbfeb08565f887d6a6.png"></p>
<ul>
<li><p>三种链接方式</p>
<ol>
<li><strong>静态链接</strong><br>装入前链接成一个完整模块</li>
<li><strong>装入时动态链接</strong><br>运行前边装入边链接</li>
<li><strong>运行时动态链接</strong><br>运行时需要什么模块才装入并链接</li>
</ol>
</li>
<li><p>三种装入方式</p>
<ol>
<li><strong>绝对装入</strong><br>编译时产生绝对地址，只适用于单道程序环境(那时候还没有操作系统，编译器负责实现)</li>
<li><strong>可重定位装入(静态重定位)</strong><br>编译链接后的装入模块地址是逻辑地址，装入时进行重定位，将指令中逻辑地址+装入的起始物理地址得到真实的物理地址<br>一个作业装入内存时，<strong>必需分配其要求的全部内存空间</strong>，内存不够就不能装入<br>作业一旦进入内存，<strong>运行期间就不能再移动，也不能再申请内存空间，因为地址都写死了</strong><br>早期多道批处理操作系统使用</li>
<li><strong>动态运行时装入(动态重定位)</strong><br>运行时才将逻辑地址转换为物理地址，需要设置**重定位寄存器(或者叫基址寄存器)**允许程序在内存中发生移动，而且程序可以分配到不连续的储存区，也支持动态申请内存<br>只需装入部分代码即可投入运行，可以向用户提供一个比存储空间大得多的地址空间<br>现代操作系统使用</li>
</ol>
</li>
</ul>
<h1 id="内存空间分配与回收"><a href="#内存空间分配与回收" class="headerlink" title="内存空间分配与回收"></a>内存空间分配与回收</h1><h2 id="连续分配管理方式"><a href="#连续分配管理方式" class="headerlink" title="连续分配管理方式"></a>连续分配管理方式</h2><p>为用户进程分配的内存必须是一个连续的内存空间</p>
<ul>
<li><strong>单一连续分配</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/0081a0e4a2e83c34175718736ba82557.png"></p>
<ul>
<li><strong>固定分区分配</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/5058bbf39550bd01e121ff658145bcd0.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/67c30dbd1599bee950756f950ef917ca.png"></p>
<ul>
<li><strong>动态分区分配</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/08767bf29ec2c778d70e77b5f4b1ab02.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/9d28c7547a80d70088163e835a6a5b0d.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/dfd3883c7a984ac035dcfbbe0394ce49.png"></p>
<blockquote>
<p>回收内存时，回收区前后的空闲分区应该合并</p>
</blockquote>
<ul>
<li><strong>动态分区分配算法</strong><ol>
<li><strong>首次适应(First Fit)</strong><br>空闲分区按地址递增顺序排列，每次分配内存时查找空闲分区链(表)，找到第一个满足要求的分区即可<br>每次从低地址部分查找，高地址的大分区更有可能被保存下来<br>效果最佳</li>
<li><strong>最佳适应(Best Fit)</strong><br>空闲分区按容量递增顺序链接，每次分配内存时按顺序查找内存分区链(表)，找到第一个可以满足的空闲分区<br>优先使用最小连续内存区，尽可能多的留下大块空闲区，满足大进程需求，但是会留下非常多难以利用的外部碎片</li>
<li><strong>最坏适应(Worst Fit)</strong><br>有叫最大适应算法(Largest Fit)<br>空闲分区按容量递减顺序排序，每次分配找到能满足要求的第一个空闲分区<br>优先使用最大的连续空闲区，使得分配后的剩余空闲区不会太少，方便使用，但是如果后面需要大内存区间就没办法了</li>
<li><strong>邻近适应(Next Fit)</strong><br>又叫循环首次适应算法<br>空闲分区按地址递增顺序构成循环链表，每次内存分配时从刚才查找结束位置开始，找到第一个能满足要求的空闲分区<br>无论是低地址还是高地址的空闲分区，都有相同的概率被使用，导致最后无大分区可用​</li>
<li><strong>对比</strong></li>
</ol>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/50d2425ddf6b7419c25b81048e422055.png"></p>
<h2 id="非连续分配管理方式"><a href="#非连续分配管理方式" class="headerlink" title="非连续分配管理方式"></a>非连续分配管理方式</h2><p>为用户进程分配的内存可以是一个分散的内存空间<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/28aefd8d61408a8fc73fa4de0eb88cb9.png"></p>
<h3 id="基本分页存储管理"><a href="#基本分页存储管理" class="headerlink" title="基本分页存储管理"></a>基本分页存储管理</h3><h4 id="分页管理"><a href="#分页管理" class="headerlink" title="分页管理"></a>分页管理</h4><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/9aa76ab94a1dbfae0f77f253568a809a.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/b95575785e694b93bba47d918ef7ed94.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/09faeccfa419d0484cda4eeaea7080f3.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/0fec9bc2dfe05653f27ef07bccbcf388.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/a3133228d3b4efc94a2469d17d0b5203.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/36b98f7da4ecbc6b1e226b84d7135526.png"></p>
<blockquote>
<p>基本分页存储管理的思想：把内存分成一个个相等的小分区，在按分区大小把进程拆分成一个个小部分 (x)</p>
</blockquote>
<h4 id="基本地址变换机构"><a href="#基本地址变换机构" class="headerlink" title="基本地址变换机构"></a>基本地址变换机构</h4><ul>
<li><p>页表寄存器(PTR)<br>  保存页表在内存中的起始地址F和页表长度M<br>  进程未执行的时候，F和M放在PCB中，进程被调度时，操作系统内核将其放到PTR中</p>
</li>
<li><p>地址转换过程</p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/2eb2b028d5cd785c98260d6fbc118c24.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/b8eaa75727fb2d37f95172d5dcd91c50.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/c12017d76287105807bebd09920d3783.png"></p>
<ul>
<li>对页表项目的探讨</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/2154b9952fc29517e016662477ea7b1b.png"></p>
<h4 id="快表地址变换机构"><a href="#快表地址变换机构" class="headerlink" title="快表地址变换机构"></a>快表地址变换机构</h4><ul>
<li><p>局部性原理</p>
<ol>
<li>时间局部性:如果执行了程序中的某条指令,那么不久后这条指令很有可能再次执行;如果某个数据被访问过,不久之后该数据很可能再次被访问。(因为程序中存在大量的循环)</li>
<li>空间局部性:一旦程序访问了某个存储单元,在不久之后,其附近的存储单元也很有可能被访问。(因为很多数据在内存中都是连续存放的）</li>
</ol>
</li>
<li><p>什么是快表(TLB)<br>  又称联想寄存器(TLB) ,是一种访问速度比内存快很多的高速缓冲存储器,用来存放当前访问的若干页表项,以加速地址变换的过程。与此对应,内存中的页表常称为慢表。</p>
</li>
<li><p>地址变换过程</p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/ec475874aa13a75c6efae864ad8089bb.png"></p>
<h4 id="两级页表"><a href="#两级页表" class="headerlink" title="两级页表"></a>两级页表</h4><ul>
<li><p>单级页表的问题<br>Q1：所有的页表项都要连续存放，页表很大时，需要占用很多很多个连续的页框。<br>比如32位逻辑地址分页储存，页面大小4K，则页表最多2^20项，一项占4B，一共需要1024个连续的页框才能放得下<br>Q2：没有必要让整个页表常驻内存，进程在一段时间可能只访问某几个特定的页面</p>
</li>
<li><p>两级页表原理</p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/76d6a57cd465b8976246e5e9196edc2e.png"></p>
<ul>
<li>如何实现地址变换</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/657bc76d734af9c9af1d0a9464585fc3.png"></p>
<ul>
<li>注意事项</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/dec992c358e87fa5e9f4fd8b36c3ea51.png"></p>
<h3 id="基本分段存储管理"><a href="#基本分段存储管理" class="headerlink" title="基本分段存储管理"></a>基本分段存储管理</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/16e9a89e972005edfe77c27ae941e8f2.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/7996687da1d81625eb2e670b73bf4631.png"></p>
<ul>
<li><strong>什么是段表</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/04c6fd47091dcdf52e5a5bed77b9ff8a.png"></p>
<ul>
<li><strong>如何实现地址变换</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/263cf986df0af5c56a30be57805b6bcf.png"></p>
<ul>
<li><strong>分段VS分页</strong>-</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/7158352d0aca697027068159d02d8cd8.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/8ab1305deb6e4491afc4e182ac4b9d0b.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/83f024c57174873268a1e390b80a2e68.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/242d7ee1fa0e36a0309c03ec7eb7a326.png"></p>
<h3 id="段页式存储管理"><a href="#段页式存储管理" class="headerlink" title="段页式存储管理"></a>段页式存储管理</h3><ul>
<li>分段分页的优缺点</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/391b4cf087b6c14ebbb1766382492a23.png"></p>
<ul>
<li><strong>段页式管理</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/137833abba4059c0befbb3b083a488a1.png"><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/203f30c57ff875d37631b93836ab3cec.png"></p>
<ul>
<li><strong>段表、页表</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/efc6d68c9181d25b30b1f1d2dd93bfad.png"></p>
<ul>
<li><strong>如何实现地址变换</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/cc29b1687f721912dec313f5802eeb7f.png"></p>
<h1 id="内存空间的扩充"><a href="#内存空间的扩充" class="headerlink" title="内存空间的扩充"></a>内存空间的扩充</h1><h2 id="覆盖技术"><a href="#覆盖技术" class="headerlink" title="覆盖技术"></a>覆盖技术</h2><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/b8d088c6d7e777d60267200f96df9531.png"></p>
<h2 id="交换-对换-技术"><a href="#交换-对换-技术" class="headerlink" title="交换(对换)技术"></a>交换(对换)技术</h2><p>内存紧张时，把进程暂时换出到外存（例：进程的中级调度(内存调度)，挂起态，七状态模型）<br>磁盘分为对换区(swap)和文件区，前者连续分配追求I/O速度，后者离散分配追求存储空间利用率<br>优先换出阻塞进程、低优先级进程（可能导致饥饿）、还要考虑进程在内存的驻留时间，PCB不会换出</p>
<h2 id="虚拟储存技术"><a href="#虚拟储存技术" class="headerlink" title="虚拟储存技术"></a>虚拟储存技术</h2><ul>
<li>传统存储方式的缺点<br>  连续分配/非连续分配<ol>
<li>一次性<br>作业必须一次性全部装入内存后才能开始运行。大作业无法运行,多道程序并发度下降。</li>
<li>驻留性<br>作业在运行期间一直驻留在内存，内存中驻留大量的暂时用不到的数据，浪费了宝贵的内存资源。</li>
</ol>
</li>
<li>局部性原理    <ol>
<li>时间局部性<br>现在访问的指令、数据在不久后很可能再次访问</li>
<li>空间局部性<br>现在访问的内存单元周围的内存空间很可能在不久之后访问</li>
<li>高速缓存<br>频繁访问的数据放到更高速的储存器中</li>
</ol>
</li>
<li>虚拟内存的定义和特征<br>  程序不需要全部装入内存即可运行，运行时根据需要动态调入数据，内存不够时，换出一些数据到外存<ol>
<li>多次性<br>作业无需在运行时一次装入内存，而是允许分多次调用</li>
<li>对换性<br>作业无需在运行时常驻内存，允许作业换入、换出</li>
<li>虚拟性<br>从逻辑上扩充了内存容量，用户看到的容量，远大于实际容量</li>
</ol>
</li>
</ul>
<div class="note warning simple"><p>虚拟内存的<strong>最大容量</strong>是由计算机的地址结构（CPU寻址范围）确定的<br>虚拟内存的<strong>实际容量</strong>=min（内存和外存容量之和，CPU寻找范围）</p>
</div>
<h1 id="如何实现虚拟内存"><a href="#如何实现虚拟内存" class="headerlink" title="如何实现虚拟内存"></a>如何实现虚拟内存</h1><h2 id="请求调页"><a href="#请求调页" class="headerlink" title="请求调页"></a>请求调页</h2><p>访问的信息不存在时，操作系统负责将需要的信息从外存调入内存</p>
<h2 id="页面置换"><a href="#页面置换" class="headerlink" title="页面置换"></a>页面置换</h2><p>内存空间不足时，将内存中暂时不用的信息换到外存<br>页面的换入换出需要磁盘I/O，时间开销是很大的，缺页率越小越好</p>
<h3 id="最佳置换算法OPT"><a href="#最佳置换算法OPT" class="headerlink" title="最佳置换算法OPT"></a>最佳置换算法OPT</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/a31e68c46d08157aff900e68175fcdb7.png"></p>
<h3 id="先进先出置换算法FIFO"><a href="#先进先出置换算法FIFO" class="headerlink" title="先进先出置换算法FIFO"></a>先进先出置换算法FIFO</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/8fbfe8dec801c9679911f48024b89abe.png"></p>
<h3 id="最近最久未使用算法LRU"><a href="#最近最久未使用算法LRU" class="headerlink" title="最近最久未使用算法LRU"></a>最近最久未使用算法LRU</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/12db53c5ecacba69329f1a320fd0f6ec.png"></p>
<h3 id="时钟置换算法CLOCK"><a href="#时钟置换算法CLOCK" class="headerlink" title="时钟置换算法CLOCK"></a>时钟置换算法CLOCK</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/3fbda0061a096757ee0b6d7975e53ed3.png"></p>
<ul>
<li><strong>改进型时钟置换算法</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/fbc5786e66054fa21ae3e66f4636370e.png"></p>
<h3 id="对比"><a href="#对比" class="headerlink" title="对比"></a>对比</h3><p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/6367b523aa247845d9ad05bbde1f773c.png"></p>
<h2 id="虚拟内存的实现"><a href="#虚拟内存的实现" class="headerlink" title="虚拟内存的实现"></a>虚拟内存的实现</h2><h3 id="请求分页存储管理"><a href="#请求分页存储管理" class="headerlink" title="请求分页存储管理"></a>请求分页存储管理</h3><ul>
<li><strong>页表机制</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/87530d9abd6297d27c42da9d19b5e2e3.png"></p>
<ul>
<li><p><strong>缺页中断机构</strong></p>
<ul>
<li>访问的页面不存在时，产生缺页中断(属于内中断的故障 fault)，操作系统缺页中断处理程序中断，进程放到阻塞队列，待调页完成后将进程唤醒，放到就绪队列</li>
<li>如果内存有空闲块，则为进程分配一个空闲块，将缺页装入其中，并修改页表相应页表项</li>
<li>如果内存没有空闲块，由页面置换算法选择一个页面淘汰(若该页面在内存期间被修改过，则需要先将其写回外存)，腾出一个空间再装入缺页​​</li>
<li>一条指令执行期间，可能产生多次缺页中断</li>
</ul>
</li>
<li><p><strong>地址变换机构</strong></p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/0e3537ef13a2ea5aca18407cb91af5ab.png"></p>
<h2 id="请求分段存储管理"><a href="#请求分段存储管理" class="headerlink" title="请求分段存储管理"></a>请求分段存储管理</h2><h2 id="请求段页式存储管理"><a href="#请求段页式存储管理" class="headerlink" title="请求段页式存储管理"></a>请求段页式存储管理</h2><h1 id="内存保护"><a href="#内存保护" class="headerlink" title="内存保护"></a>内存保护</h1><p>进程1只能访问进程1的内存，不能越界访问其它进程或者操作系统的内存区<br>方法一：在CPU中设置上限/下限寄存器，保存进程可访问的物理地址的上下限<br>方法二：重定位寄存器(基址寄存器)+界地址寄存器(限长寄存器)<br>重定位寄存器中保存了进程的起始物理地址P1，界地址寄存器保存了进程的最大逻辑地址P2, 进程可以访问的物理内存位置是P1~P1+P2</p>
<h1 id="页面分配策略"><a href="#页面分配策略" class="headerlink" title="页面分配策略"></a>页面分配策略</h1><ul>
<li><strong>相关概念</strong></li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/e5e89721b565c0911c692b8012b2892e.png"></p>
<ul>
<li><p><strong>固定分配局部置换</strong>)</p>
<ul>
<li>系统为每个进程分配一定数量的物理块,在整个运行期间都不改变。</li>
<li>若进程在运行中发生缺页,则只能从该进程在内存中的页面中选出一页换出,然后再调入需要的页面。</li>
<li>缺点:很难在刚开始就确定应为每个进程分配多少个物理块才算合理。(采用这种策略的系统可以根据进程大小、优先级、或是根据程序员给出的参数来确定为一个进程分配的内存块数)</li>
</ul>
</li>
<li><p><strong>可变分配全局置换</strong></p>
<ul>
<li>刚开始会为每个进程分配一定数量的物理块。操作系统会保持一个空闲物理块队列。</li>
<li>当某进程发生缺页时,从空闲物理块中取出一块分配给该进程;若已无空闲物理块,则可选择一个未锁定的页面换出外存,再将该物理块分配给缺页的进程。</li>
<li>只要某进程缺页,都将获得新的物理块,仅当空闲物理块用完时,系统才选择一个未锁定的页面调出。</li>
<li>被选择调出的页可能是系统中任何一个进程中的页,因此这个被选中的进程拥有的物理块会减少,缺页率会增加。</li>
</ul>
</li>
<li><p><strong>可变分配局部置换</strong></p>
<ul>
<li>刚开始会为每个进程分配一定数量的物理块。当某进程发生缺页时,只允许从该进程自己的物理块中选出一个进行换出外存。</li>
<li>如果进程在运行中频繁地缺页,系统会为该进程多分配几个物理块,直至该进程缺页率趋势适当程度;</li>
<li>反之,如果进程在运行中缺页率特别低,则可适当减少分配给该进程的物理块。</li>
</ul>
</li>
<li><p><strong>调入页面的时机</strong></p>
<ul>
<li><strong>预调页策略</strong><br>  运行前调入，根据空间局部性原理,一次调入若干个相邻的页面可能比一次调入一个页面更高效。但如果提前调入的页面中大多数都没被访问过,则又是低效的。<br>  因此可以预测不久之后可能访问到的页面,将它们预先调入内存,但目前预测成功率只有50%左右。故这种策略主要用于进程的首次调入,由程序员指定应该调入的部分。</li>
<li><strong>请求调页策略</strong><br>运行时调入，进程在运行期间发现缺页时才将所缺页面调入内存。由这种策略调入的页面一定会被访问到,但由于每次只能调入一页,而每次调页都要磁盘I/O操作,因此I/O开销较大。</li>
</ul>
</li>
<li><p><strong>从何处调页</strong></p>
<ul>
<li><strong>对换区空间足够</strong><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/cf3dd8df63ee90c85d95c7c43987561e.png"></li>
<li><strong>对换区空间不够</strong><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/258a8a5c20df486e189abb531c735fa3.png"></li>
<li><strong>Unix方式</strong><br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/2d352762246646b4e081b7b4e4f8e2e7.png"></li>
</ul>
</li>
<li><p><strong>抖动(颠簸)现象</strong><br>给进程分配的物理块太少，刚刚换出的页面马上又要换入内存,刚刚换入的页面马上又要换出外存，这种频繁的页面调度行为称为抖动或颠簸。</p>
</li>
<li><p><strong>工作集</strong></p>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/29/c3e0c087bb7b935766cc5956a55a248b.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">xiaoliblog</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/os05.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">操作系统⚡文件管理</div></div></a></div><div class="next-post pull-right"><a href="/page/os03.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">操作系统⚡进程管理</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/page/os02.html" title="操作系统⚡概述"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">操作系统⚡概述</div></div></a></div><div><a href="/page/os01.html" title="操作系统⚡I/O管理"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">操作系统⚡I/O管理</div></div></a></div><div><a href="/page/os05.html" title="操作系统⚡文件管理"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">操作系统⚡文件管理</div></div></a></div><div><a href="/page/os03.html" title="操作系统⚡进程管理"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@46194ca18065ae5d399864564e6f718045a04d48/2021/01/24/1a8d51f216a11fa2f3a7fb50049f1f1d.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-15</div><div class="title">操作系统⚡进程管理</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">内存管理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E5%9F%BA%E7%A1%80"><span class="toc-number">1.1.</span> <span class="toc-text">内存基础</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E5%88%86%E9%85%8D%E4%B8%8E%E5%9B%9E%E6%94%B6"><span class="toc-number">2.</span> <span class="toc-text">内存空间分配与回收</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%9E%E7%BB%AD%E5%88%86%E9%85%8D%E7%AE%A1%E7%90%86%E6%96%B9%E5%BC%8F"><span class="toc-number">2.1.</span> <span class="toc-text">连续分配管理方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9D%9E%E8%BF%9E%E7%BB%AD%E5%88%86%E9%85%8D%E7%AE%A1%E7%90%86%E6%96%B9%E5%BC%8F"><span class="toc-number">2.2.</span> <span class="toc-text">非连续分配管理方式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E5%88%86%E9%A1%B5%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">2.2.1.</span> <span class="toc-text">基本分页存储管理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E7%AE%A1%E7%90%86"><span class="toc-number">2.2.1.1.</span> <span class="toc-text">分页管理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E5%9C%B0%E5%9D%80%E5%8F%98%E6%8D%A2%E6%9C%BA%E6%9E%84"><span class="toc-number">2.2.1.2.</span> <span class="toc-text">基本地址变换机构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BF%AB%E8%A1%A8%E5%9C%B0%E5%9D%80%E5%8F%98%E6%8D%A2%E6%9C%BA%E6%9E%84"><span class="toc-number">2.2.1.3.</span> <span class="toc-text">快表地址变换机构</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%A4%E7%BA%A7%E9%A1%B5%E8%A1%A8"><span class="toc-number">2.2.1.4.</span> <span class="toc-text">两级页表</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E5%88%86%E6%AE%B5%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">2.2.2.</span> <span class="toc-text">基本分段存储管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%AE%B5%E9%A1%B5%E5%BC%8F%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">2.2.3.</span> <span class="toc-text">段页式存储管理</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E7%9A%84%E6%89%A9%E5%85%85"><span class="toc-number">3.</span> <span class="toc-text">内存空间的扩充</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A6%86%E7%9B%96%E6%8A%80%E6%9C%AF"><span class="toc-number">3.1.</span> <span class="toc-text">覆盖技术</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%A4%E6%8D%A2-%E5%AF%B9%E6%8D%A2-%E6%8A%80%E6%9C%AF"><span class="toc-number">3.2.</span> <span class="toc-text">交换(对换)技术</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E6%8B%9F%E5%82%A8%E5%AD%98%E6%8A%80%E6%9C%AF"><span class="toc-number">3.3.</span> <span class="toc-text">虚拟储存技术</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E8%99%9A%E6%8B%9F%E5%86%85%E5%AD%98"><span class="toc-number">4.</span> <span class="toc-text">如何实现虚拟内存</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E8%B0%83%E9%A1%B5"><span class="toc-number">4.1.</span> <span class="toc-text">请求调页</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B5%E9%9D%A2%E7%BD%AE%E6%8D%A2"><span class="toc-number">4.2.</span> <span class="toc-text">页面置换</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%80%E4%BD%B3%E7%BD%AE%E6%8D%A2%E7%AE%97%E6%B3%95OPT"><span class="toc-number">4.2.1.</span> <span class="toc-text">最佳置换算法OPT</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%88%E8%BF%9B%E5%85%88%E5%87%BA%E7%BD%AE%E6%8D%A2%E7%AE%97%E6%B3%95FIFO"><span class="toc-number">4.2.2.</span> <span class="toc-text">先进先出置换算法FIFO</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%80%E8%BF%91%E6%9C%80%E4%B9%85%E6%9C%AA%E4%BD%BF%E7%94%A8%E7%AE%97%E6%B3%95LRU"><span class="toc-number">4.2.3.</span> <span class="toc-text">最近最久未使用算法LRU</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%97%B6%E9%92%9F%E7%BD%AE%E6%8D%A2%E7%AE%97%E6%B3%95CLOCK"><span class="toc-number">4.2.4.</span> <span class="toc-text">时钟置换算法CLOCK</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E6%AF%94"><span class="toc-number">4.2.5.</span> <span class="toc-text">对比</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E6%8B%9F%E5%86%85%E5%AD%98%E7%9A%84%E5%AE%9E%E7%8E%B0"><span class="toc-number">4.3.</span> <span class="toc-text">虚拟内存的实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%88%86%E9%A1%B5%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">4.3.1.</span> <span class="toc-text">请求分页存储管理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%88%86%E6%AE%B5%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">4.4.</span> <span class="toc-text">请求分段存储管理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E6%AE%B5%E9%A1%B5%E5%BC%8F%E5%AD%98%E5%82%A8%E7%AE%A1%E7%90%86"><span class="toc-number">4.5.</span> <span class="toc-text">请求段页式存储管理</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E4%BF%9D%E6%8A%A4"><span class="toc-number">5.</span> <span class="toc-text">内存保护</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%A1%B5%E9%9D%A2%E5%88%86%E9%85%8D%E7%AD%96%E7%95%A5"><span class="toc-number">6.</span> <span class="toc-text">页面分配策略</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>